import fetch from 'node-fetch';
import { segment } from 'icqq';
import http from 'http'
import https from 'https'


export class site extends plugin {
    constructor() {
      super({
        name: 'Yunzai_Bot_site',
        dsc: '网站模块',
        event: 'message',
        priority: 600,
        rule: [
          {
            reg: /^(#|\/)cdn.*/,
            fnc: 'cdn',
          },
          {
            reg: /^(#|\/)备案.*/,
            fnc: 'beian',
          },
         {
            reg: /^(#|\/)收录.*/,
            fnc: 'shoulu',
          }, 
          {
            reg: /^(#|\/)ping.*/,
            fnc: 'pingweb',
          },
          // {
          //   reg: /^(#|\/)访问量.*/,
          //   fnc: 'getWebsiteViews',
          // }
          {
            reg: /^(#|\/)测速.*/,
            fnc: 'suweb',
          }
        ],
      });
    }
    async cdn(e){
      let usr_qq = e.user_id;
      let didian = e.msg.replace(/(\/|#)cdn/, '').trim();
      await testCDNUsage(e,usr_qq,didian)

async function testCDNUsage(e,usr_qq,url) {
  try {
    const options = {
      method: 'HEAD',
      headers: {
        'User-Agent': 'Mozilla/5.0', // 设置用户代理以避免被阻止或过滤
      },
    };

    const response = await new Promise((resolve, reject) => {
      const protocol = url.startsWith('https://') ? https : http;
      const req = protocol.request(url, options, resolve);
      req.on('error', reject);
      req.end();
    });

    if (response.headers['x-cache'] || response.headers.server.includes('CDN')) {
      console.log(`网站 ${url} 使用了 CDN`);
    } else {
      console.log(`网站 ${url} 没有使用 CDN`);
    }
  } catch (error) {
    console.error('发生错误：', error);
  }
}

    }
    async beian(e){
      let usr_qq = e.user_id;
      let didian = e.msg.replace(/(\/|#)备案/, '').trim();
      await checkWebsiteFilingStatus(e,usr_qq,didian)
      async function checkWebsiteFilingStatus(e,usr_qq,domain) {
      try {
        const apiUrl = `https://www.mxnzp.com/api/beian/search?domain=${encodeURIComponent(domain)}`;
    
        const response = await fetch(apiUrl);
        const data = await response.json();
    
        if (data.code === 1 && data.data) {
          const filingStatus = data.data.status;
          console.log(`网站 ${domain} 备案状态：${filingStatus}`);
          e.reply([segmen.at(usr_qq),`网站备案状态：${filingStatus}`]);
        } else {
          console.log(`无法获取网站 ${domain}的备案信息`);
          e.reply([segment.at(usr_qq),`无法获取网站的备案信息`]);
        }
      } catch (error) {
        console.error('发生错误：', error);
        e.reply('发生错误')
      }
    }
  }

    
    async suweb(e){
      const startTime = Date.now();
      let usr_qq = e.user_id;
      let didian = e.msg.replace(/(\/|#)测速/, '').trim();
      try {
        const protocol = didian.startsWith('https') ? https : http;
        await new Promise((resolve, reject) => {
          protocol.get(didian, (res) => {
            res.on('data', () => {});
            res.on('end', resolve);
          }).on('error', reject);
        });
    
        const endTime = Date.now();
        const responseTime = endTime - startTime;
    
        console.log(`网站的响应时间为：${responseTime}ms`);
        e.reply([segment.at(usr_qq),`网站的响应时间为：${responseTime}ms`]);
      } catch (error) {
        console.error('发生错误：', error);
        e.reply('发生错误')
      }
    }
    

    // async getWebsiteViews(e){
    //   let usr_qq = e.user_id;
    //   let didian = e.msg.replace(/(\/|#)访问量/, '').trim();
    //   try {
    //     const websiteUrl = didian; 
  
    //     const apiUrl = `https://api.statcounter.com/stats/?stat=pageviews&project=YOUR_PROJECT_ID&u=${websiteUrl}`;
  
    //     const response = await fetch(apiUrl);
    //     const data = await response.text();
  
    //     e.reply(`网站访问量：${data}`);
    //   } catch (error) {
    //     console.error('发生错误：', error);
    //     e.reply('无法获取网站访问量');
    //   }
    // }
    async pingweb(e) {
      let usr_qq = e.user_id;
      let didian = e.msg.replace(/(\/|#)ping/, '').trim();
  
      const startTime = Date.now(); // 记录开始时间
  
      try {
        const response = await fetch(didian);
        const endTime = Date.now(); // 记录结束时间
  
        const elapsedTime = endTime - startTime; // 计算耗时（毫秒）
  
        e.reply([segment.at(usr_qq),`Ping成功，网站访问耗时：${elapsedTime}ms`]);
      } catch (error) {
        console.error('发生错误：', error);
        e.reply('Ping失败');
      }
    }
  
  
  async shoulu(e) {
    let usr_qq = e.user_id;
    let didian = e.msg.replace(/(\/|#)收录/, '').trim();

    // 使用搜索引擎查询域名的收录数量
    let searchEngines = ['谷歌', '必应', '百度', '搜狗']; // 可以添加其他搜索引擎
    let results = {};

    for (let engine of searchEngines) {
      let count = await querySiteIndex(engine, didian);
      results[engine] = count;
    }

    // 构建返回消息
    // let message = `域名 ${didian} 的收录情况如下：\n`;
    let message = `网站的收录情况如下：\n`;
    for (let engine in results) {
      message += `${engine}: `;
      if (results[engine] === null) {
        message += '无法响应\n';
      } else {
        message += `${results[engine]} 条\n`;
      }
    }

    // 将结果发送给用户
    console.log([usr_qq, `\n${message}`]);
    e.reply([segment.at(usr_qq),`\n${message}`])
  }
}

// 查询指定搜索引擎中域名的收录数量
async function querySiteIndex(engine, domain) {
  let searchUrl = ''; // 存储搜索引擎的查询URL

  switch (engine) {
    case '谷歌':
      searchUrl = `https://www.google.com/search?q=site:${domain}`;
      break;
    case '必应':
      searchUrl = `https://www.bing.com/search?q=site:${domain}`;
      break;
    case '百度':
      searchUrl = `https://www.baidu.com/s?wd=site:${domain}`;
      break;
    case '搜狗':
      searchUrl = `https://www.sogou.com/web?query=site:${domain}`;
      break;
    default:
      return null; // 搜索引擎不支持或未知引擎，返回null表示无法响应
  }

  try {
    const response = await fetch(searchUrl);
    const html = await response.text();

    // 在这里解析HTML页面，提取出收录数量
    const count = parseCountFromHtml(engine, html);

    return count;
  } catch (error) {
    console.error(`查询${engine}收录数量时出错：`, error);
    if (engine === '谷歌') {
      return null; // 谷歌无法响应，返回null表示无法响应
    } else {
      return 0; // 其他搜索引擎发生错误，返回收录数量为0
    }
  }
}

// 解析HTML页面，提取出收录数量的函数
function parseCountFromHtml(engine, html) {
  let count = 0;

  switch (engine) {
    case '谷歌':
      // 示例代码：
      const googleRegex = /找到约([\d,.]+)个结果/i;
      const googleMatch = html.match(googleRegex);
      if (googleMatch && googleMatch[1]) {
        count = parseInt(googleMatch[1].replace(/[,|.]/g, ''));
      }
      break;
    case '必应':
      // 示例代码：
      const bingRegex = /共 ([\d,.]+) 条结果/i;
      const bingMatch = html.match(bingRegex);
      if (bingMatch && bingMatch[1]) {
        count = parseInt(bingMatch[1].replace(/[,|.]/g, ''));
      }
      break;
    case '百度':
      // 示例代码：
      const baiduRegex = /找到相关结果([\d,.]+)个/i;
      const baiduMatch = html.match(baiduRegex);
      if (baiduMatch && baiduMatch[1]) {
        count = parseInt(baiduMatch[1].replace(/[,|.]/g, ''));
      }
      break;
    case '搜狗':
      // 示例代码：
      const sogouRegex = /找到约([\d,.]+)条结果/i;
      const sogouMatch = html.match(sogouRegex);
      if (sogouMatch && sogouMatch[1]) {
        count = parseInt(sogouMatch[1].replace(/[,|.]/g, ''));
      }
      break;
    default:
      count = 0; // 搜索引擎不支持或未知引擎，返回收录数量为0
  }

  return count;
}
